// pages/home/home.js
var app = getApp();
var server = require('../../utils/server');
const util = require("../../utils/util.js")
Page({

  /**
   * 页面的初始数据
   */ 
  data: {
    UserID:0, //用户ID
    NickName:'',  //昵称
    HeadImg:'', //用户头像
    hiddenLoading: true,
    Address: '定位中',
    imgUrls: [
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    classifyItem: [{
      "id":1,
      "image": "../../image/index_02.png",
      "text": "餐饮美食"
    }, {
      "id":2,
      "image": "../../image/index_03.png",
      "text": "酒店娱乐"
    }, {
      "id": 3,
      "image": "../../image/index_04.png",
      "text": "生活服务"
    }, {
      "id": 4,
      "image": "../../image/index_05.png",
      "text": "超市百货"
    }],
    hotItem: [{
      "hotImage": "../../image/bg.png",
      "hotText": "天天水果店"
    }, {
      "hotImage": "../../image/bg.png",
      "hotText": "天天水果店1"
    }]
  },
  onLoad: function (options) {  
    this.ShowLoading(); //显示加载
    this.GetAddress();//获取地理位置
  
    this.GetAdList(); //获取轮播图
    this.GetHotTuiJian(); //获取推荐商家    
    //this.GetSupplierList(); //获取优惠商家
    var that = this;    
    
  },
  onHide: function () {
    util.GetUserInfo("您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。"); //获取用户信息    
  },
  //定位跳转
  siteSearch: function(){
    wx.navigateTo({
      url: '../location/location'
    })
  },
  //搜索跳转
  bisSearch:function(){
    wx.navigateTo({
      url: 'merchant/merchant'
    })
  },
  //分类跳转
  classifyItem:function(e){
    var typeid = e.currentTarget.dataset.typeid;
    var title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: 'more/more?typeid='+typeid+'&title='+title
    })
  },
  //更多商户
  more:function(){
    wx.navigateTo({
      url: 'more/more'
    })
  },
  //详情
  goDetail:function(e){
    var sid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'detail/detail?sid=' + sid
    })
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function (options) {
    this.ShowLoading();
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
  },
  ShowLoading:function(){
    this.setData({
      hiddenLoading: false
    });
    var that = this;
    setTimeout(function () {
      wx.stopPullDownRefresh();
      that.setData({
        hiddenLoading: true
      });
    }, 1000);
  },  
  GetAddress:function(){  //获取地理位置
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {        
        that.AddressInfo(res);
        that.GetSupplierList(res.latitude, res.longitude); //重新加载优惠商家
        that.GetUserInfo();
      },
      fail: function () {
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权,将无法正常地理位置信息,点击确定重新获取授权。',
          success: function (res) {
            //console.log(res);
            if (res.confirm) {
              wx.openSetting({
                success: function (datas) {
                  if (datas.authSetting["scope.userLocation"]){                    
                    wx.getLocation({
                      success: function (res) {
                        that.AddressInfo(res);
                        that.GetSupplierList(res.latitude,res.longitude); //重新加载优惠商家
                        that.GetUserInfo();
                      }
                    })
                  }else{
                    that.GetAddress();
                  }            
                }
              })
            }else{
              that.GetAddress();
            }
          },
          fail: function () { }
        })
      }
    })
  },
  AddressInfo: function (res) { //地址信息

    var that = this;
    var latitude = res.latitude;
    var longitude = res.longitude;
    util.GetAddressByPosition(latitude, longitude, function (e) {
      var recommend = e.result.formatted_addresses.recommend;
      var city = e.result.address_component.city;
      var area = e.result.address_component.district;
      //var address = recommend.replace(area,'');   //将区县 替换掉
      //that.setData({ Address:address})
      that.setData({ Address: recommend })
      wx.setStorageSync('AddressInfo',e.result);  //本地存储 地址信息
      that.GetSupplierList(e.result.location.lat, e.result.location.lng);
    });
  },
  GetUserInfo:function(){ //获取个人信息
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.globalData.domainName + '/tools/API.ashx?act=GetOpenID&code=' + res.code,
          method: 'GET',
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (openIdRes) {
            wx.setStorageSync('openids', openIdRes.data)
            util.GetUserInfo("您点击了拒绝授权,将无法正常显示个人信息,点击确定重新获取授权。");
          }
        })

      }
    })

  },

  GetAdList:function(){  //动态获取图片
    var that = this;        
    var data = {
      page:1,
      limit:10,
      source:4
    };
    data.act = "Find_Ad";        
    util.Ajax(data, function (json) {   
      if(json.count>0){
        var ImgUrls = new Array();
        for (var i = 0; i <json.count;i++){
          ImgUrls.push(json.data[i].Img);
        }
        that.setData({ imgUrls: ImgUrls});
      }else{
        that.setData({
          imgUrls: [
            'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
            'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
            'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
          ]})
      }
    });
  },
  GetHotTuiJian:function(){ //获取热门推荐
    var that = this;
    var data = {
      page: 1,
      limit: 5
    };
    data.act = "Find_Supplier";
    util.Ajax(data, function (json) {
      if (json.count > 0) {
        that.setData({TuiJianSupplierList:json.data});        
      } 
    });

  },
  GetSupplierList: function (lat,lng) { //获取优惠商家
    var that = this;
    if (lat == undefined){
      wx.getStorage({
        key: 'AddressInfo',
        success: function (res) {
          lat = res.data.location.lat;
          lng = res.data.location.lng;
        }
      })
    }
    var data = {
      lat: lat,
      lng: lng,
      page: 1,
      limit: 10,
      distance: 1
    };
    data.act = "Find_SupplierByTypeAndDiscountAndAddress";
    util.Ajax(data, function (json) {
      if (json.count > 0) {
        that.setData({ SupplierList: json.data, searchLoadingComplete:true});
        
      }
    });
    
  }
})

